/*
 * Copyright (c) 2017-present, CV4J Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.rxcv4j;

import com.cv4j.rxcv4j.util.LruCache;

import ohos.agp.utils.TextTool;
import ohos.media.image.PixelMap;

import java.util.Optional;

/**
 * mem缓存
 *
 * @author dev
 * @since 2021-05-17
 */
public class MemCache {
    /**
     * MemCache
     */
    public static MemCache INSTANCE = new MemCache();

    private static LruCache<String, PixelMap> mLruCache;

    /**
     * mem缓存
     */
    private MemCache() {
        int cacheSize = (int) (Runtime.getRuntime().maxMemory() / 8);
        mLruCache = new LruCache<String, PixelMap>(cacheSize) {
            @Override
            protected int getSize(PixelMap value) {
                int bitmapSize = getBitmapSize(value);
                if (bitmapSize == 0) {
                    return 1;
                } else {
                    return bitmapSize;
                }
            }

            @Override
            public synchronized Optional<PixelMap> remove(String key) {
                Optional<PixelMap> pixelMap = super.remove(key);
                if (pixelMap.isPresent() && !pixelMap.get().isReleased()) {
                    pixelMap.get().release();
                }
                return pixelMap;
            }
        };
    }

    /**
     * 清晰的
     * 清空lrucache缓存
     */
    public void clear() {
        mLruCache.clearMemory();
    }

    /**
     * 删除
     *
     * @param key 关键
     */
    public void remove(String key) {
        if (!TextTool.isNullOrEmpty(key)) {
            mLruCache.remove(key);
        }
    }

    /**
     * 把
     *
     * @param key 关键
     * @param value 价值
     */
    public synchronized void put(String key, PixelMap value) {
        mLruCache.put(key, value);
    }

    /**
     * 得到
     * get
     *
     * @param key 关键
     * @return PixelMap
     */
    public Optional<PixelMap> get(String key) {
        if (mLruCache == null) {
            return Optional.empty();
        }
        return mLruCache.get(key);
    }

    /**
     * 获取位图的大小
     * getBitmapSize
     *
     * @param value a bitmap
     * @return size of bitmap
     */
    private int getBitmapSize(PixelMap value) {
        if (value == null) {
            return 0;
        }
        return (int) value.getPixelBytesNumber();
    }
}
